﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Swagger
{
    /*
     * 使用方式如下：重写服务 swagger中的url使网关在swagger页面api调试时可以调通服务接口，但此处会破坏服务自己的swagger页面里的api地址
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "SystemApplication", Version = "v1" });
                c.DocumentFilter<HiddenApiFilter>();
                Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.xml").ToList().ForEach(file =>
                {
                    c.IncludeXmlComments(file, true);
                });
            });
     
     */
    /// <summary>
    /// swagger隐藏接口过滤器
    /// </summary>
    public class HiddenApiFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {

            OpenApiPaths newPaths = new OpenApiPaths();
            foreach (var item in swaggerDoc.Paths.Keys)
            {
                if (swaggerDoc.Info.Title == "SystemApplication")
                {
                    newPaths.Add("/system" + item, swaggerDoc.Paths[item]);
                }
            }
            swaggerDoc.Paths.Clear();
            swaggerDoc.Paths = newPaths;
        }
    }
}
